import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Button, Space, Modal, Form, Input, Select, message, Popconfirm, Switch, Tabs, Upload } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, UploadOutlined, SaveOutlined } from '@ant-design/icons';
import { request } from 'umi';

const { TabPane } = Tabs;

// 获取支付渠道列表
const fetchPaymentChannels = async (params) => {
  return request('/api/v1/payment/channel', {
    method: 'GET',
    params,
  });
};

// 创建支付渠道
const createPaymentChannel = async (data) => {
  return request('/api/v1/payment/channel', {
    method: 'POST',
    data,
  });
};

// 更新支付渠道
const updatePaymentChannel = async (data) => {
  return request('/api/v1/payment/channel', {
    method: 'PUT',
    data,
  });
};

// 删除支付渠道
const deletePaymentChannel = async (id) => {
  return request(`/api/v1/payment/channel/${id}`, {
    method: 'DELETE',
  });
};

const PaymentChannelConfig = () => {
  const [channels, setChannels] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('添加支付渠道');
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  const [activeTab, setActiveTab] = useState('all');
  const [currentChannelType, setCurrentChannelType] = useState('wechat');

  // 获取支付渠道列表
  const fetchChannelList = async () => {
    try {
      setLoading(true);
      const res = await fetchPaymentChannels({
        page: pagination.current,
        pageSize: pagination.pageSize,
        type: activeTab !== 'all' ? activeTab : undefined,
      });
      if (res.success) {
        setChannels(res.data || []);
      } else {
        message.error(res.message || '获取支付渠道列表失败');
      }
    } catch (error) {
      console.error('获取支付渠道列表出错:', error);
      message.error('获取支付渠道列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchChannelList();
  }, [pagination.current, pagination.pageSize, activeTab]);

  // 监听渠道类型变化，清空不相关的表单字段
  useEffect(() => {
    if (modalVisible) {
      const type = form.getFieldValue('type');
      if (type) {
        setCurrentChannelType(type);
        
        // 清空特定渠道的字段
        if (type === 'wechat') {
          form.setFieldsValue({
            private_key: undefined,
            public_key: undefined,
          });
        } else if (type === 'alipay') {
          form.setFieldsValue({
            app_secret: undefined,
            mch_id: undefined,
            mch_key: undefined,
            cert_path: undefined,
          });
        } else if (type === 'unionpay') {
          form.setFieldsValue({
            app_id: undefined,
            app_secret: undefined,
            private_key: undefined,
            public_key: undefined,
          });
        } else if (type === 'balance') {
          form.setFieldsValue({
            app_id: undefined,
            app_secret: undefined,
            mch_id: undefined,
            mch_key: undefined,
            cert_path: undefined,
            private_key: undefined,
            public_key: undefined,
            notify_url: undefined,
          });
        }
      }
    }
  }, [form.getFieldValue('type'), modalVisible]);

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '渠道名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '渠道代码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '渠道类型',
      dataIndex: 'type',
      key: 'type',
      render: (text) => {
        const typeMap = {
          'wechat': '微信支付',
          'alipay': '支付宝',
          'unionpay': '银联支付',
          'balance': '余额支付',
        };
        return typeMap[text] || text;
      },
    },
    {
      title: '手续费率',
      dataIndex: 'fee_rate',
      key: 'fee_rate',
      render: (text) => text ? `${text}%` : '0%',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <span style={{ color: status === 1 ? '#52c41a' : '#ff4d4f' }}>
          {status === 1 ? '启用' : '禁用'}
        </span>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此支付渠道吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="primary" 
              danger 
              icon={<DeleteOutlined />} 
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理添加支付渠道
  const handleAdd = () => {
    setModalTitle('添加支付渠道');
    setEditingId(null);
    form.resetFields();
    const defaultType = activeTab !== 'all' ? activeTab : 'wechat';
    form.setFieldsValue({ 
      status: 1,
      fee_rate: 0,
      type: defaultType,
    });
    setCurrentChannelType(defaultType);
    setModalVisible(true);
  };

  // 处理编辑支付渠道
  const handleEdit = (record) => {
    setModalTitle('编辑支付渠道');
    setEditingId(record.id);
    form.setFieldsValue({
      name: record.name,
      code: record.code,
      type: record.type,
      app_id: record.app_id,
      app_secret: record.app_secret,
      mch_id: record.mch_id,
      mch_key: record.mch_key,
      cert_path: record.cert_path,
      notify_url: record.notify_url,
      fee_rate: record.fee_rate,
      status: record.status,
    });
    setCurrentChannelType(record.type);
    setModalVisible(true);
  };

  // 处理删除支付渠道
  const handleDelete = async (id) => {
    try {
      const res = await deletePaymentChannel(id);
      if (res.success) {
        message.success('删除成功');
        fetchChannelList();
      } else {
        message.error(res.message || '删除失败');
      }
    } catch (error) {
      console.error('删除支付渠道出错:', error);
      message.error('删除失败');
    }
  };

  // 处理表单提交
  const handleSubmit = async (values) => {
    try {
      const data = { ...values };
      let res;
      
      if (editingId) {
        data.id = editingId;
        res = await updatePaymentChannel(data);
      } else {
        res = await createPaymentChannel(data);
      }
      
      if (res.success) {
        message.success(`${editingId ? '更新' : '添加'}成功`);
        setModalVisible(false);
        fetchChannelList();
      } else {
        message.error(res.message || `${editingId ? '更新' : '添加'}失败`);
      }
    } catch (error) {
      console.error(`${editingId ? '更新' : '添加'}支付渠道出错:`, error);
      message.error(`${editingId ? '更新' : '添加'}失败`);
    }
  };

  // 上传配置
  const uploadProps = {
    name: 'file',
    action: '/api/v1/upload',
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info) {
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
        form.setFieldsValue({
          certPath: info.file.response.data.url,
        });
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
  };

  // 渲染不同支付渠道的表单项
  const renderChannelFormItems = () => {
    const type = currentChannelType;
    
    switch (type) {
      case 'wechat':
        return (
          <>
            <Form.Item
              name="app_id"
              label="AppID"
              rules={[{ required: true, message: '请输入AppID' }]}
            >
              <Input placeholder="请输入AppID" />
            </Form.Item>
            
            <Form.Item
              name="app_secret"
              label="AppSecret"
              rules={[{ required: true, message: '请输入AppSecret' }]}
            >
              <Input.Password placeholder="请输入AppSecret" />
            </Form.Item>
            
            <Form.Item
              name="mch_id"
              label="商户号"
              rules={[{ required: true, message: '请输入商户号' }]}
            >
              <Input placeholder="请输入商户号" />
            </Form.Item>
            
            <Form.Item
              name="mch_key"
              label="商户密钥"
              rules={[{ required: true, message: '请输入商户密钥' }]}
            >
              <Input.Password placeholder="请输入商户密钥" />
            </Form.Item>
            
            <Form.Item
              name="cert_path"
              label="支付证书"
            >
              <Input 
                placeholder="请上传支付证书" 
                addonAfter={
                  <Upload {...uploadProps}>
                    <Button icon={<UploadOutlined />}>上传</Button>
                  </Upload>
                } 
              />
            </Form.Item>
            
            <Form.Item
              name="notify_url"
              label="回调地址"
            >
              <Input placeholder="请输入回调地址" />
            </Form.Item>
          </>
        );
      case 'alipay':
        return (
          <>
            <Form.Item
              name="app_id"
              label="AppID"
              rules={[{ required: true, message: '请输入AppID' }]}
            >
              <Input placeholder="请输入AppID" />
            </Form.Item>
            
            <Form.Item
              name="private_key"
              label="应用私钥"
              rules={[{ required: true, message: '请输入应用私钥' }]}
            >
              <Input.TextArea rows={4} placeholder="请输入应用私钥" />
            </Form.Item>
            
            <Form.Item
              name="public_key"
              label="支付宝公钥"
              rules={[{ required: true, message: '请输入支付宝公钥' }]}
            >
              <Input.TextArea rows={4} placeholder="请输入支付宝公钥" />
            </Form.Item>
            
            <Form.Item
              name="notify_url"
              label="回调地址"
            >
              <Input placeholder="请输入回调地址" />
            </Form.Item>
          </>
        );
      case 'unionpay':
        return (
          <>
            <Form.Item
              name="mch_id"
              label="商户号"
              rules={[{ required: true, message: '请输入商户号' }]}
            >
              <Input placeholder="请输入商户号" />
            </Form.Item>
            
            <Form.Item
              name="mch_key"
              label="商户密钥"
              rules={[{ required: true, message: '请输入商户密钥' }]}
            >
              <Input.Password placeholder="请输入商户密钥" />
            </Form.Item>
            
            <Form.Item
              name="cert_path"
              label="支付证书"
            >
              <Input 
                placeholder="请上传支付证书" 
                addonAfter={
                  <Upload {...uploadProps}>
                    <Button icon={<UploadOutlined />}>上传</Button>
                  </Upload>
                } 
              />
            </Form.Item>
            
            <Form.Item
              name="notify_url"
              label="回调地址"
            >
              <Input placeholder="请输入回调地址" />
            </Form.Item>
          </>
        );
      case 'balance':
        return (
          <>
            <Form.Item
              name="name"
              label="名称"
              rules={[{ required: true, message: '请输入名称' }]}
            >
              <Input placeholder="请输入名称" />
            </Form.Item>
          </>
        );
      default:
        return null;
    }
  };

  return (
    <PageContainer>
      <Card title="支付渠道配置">
        <div style={{ marginBottom: 16 }}>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={handleAdd}
          >
            添加支付渠道
          </Button>
        </div>
        
        <Tabs defaultActiveKey="all" onChange={(key) => setActiveTab(key)}>
          <TabPane tab="全部" key="all" />
          <TabPane tab="微信支付" key="wechat" />
          <TabPane tab="支付宝" key="alipay" />
          <TabPane tab="银联支付" key="unionpay" />
          <TabPane tab="余额支付" key="balance" />
        </Tabs>
        
        <Table 
          columns={columns} 
          dataSource={channels} 
          rowKey="id" 
          loading={loading}
          pagination={pagination}
          onChange={(pagination) => setPagination(pagination)}
        />
        
        <Modal
          title={modalTitle}
          visible={modalVisible}
          onCancel={() => setModalVisible(false)}
          footer={[
            <Button key="cancel" onClick={() => setModalVisible(false)}>
              取消
            </Button>,
            <Button 
              key="submit" 
              type="primary" 
              icon={<SaveOutlined />}
              onClick={() => form.submit()}
            >
              保存
            </Button>,
          ]}
          width={700}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
          >
            <Form.Item
              name="name"
              label="渠道名称"
              rules={[{ required: true, message: '请输入渠道名称' }]}
            >
              <Input placeholder="请输入渠道名称" />
            </Form.Item>
            
            <Form.Item
              name="code"
              label="渠道代码"
              rules={[{ required: true, message: '请输入渠道代码' }]}
            >
              <Input placeholder="请输入渠道代码" />
            </Form.Item>
            
            <Form.Item
              name="type"
              label="渠道类型"
              rules={[{ required: true, message: '请选择渠道类型' }]}
            >
              <Select 
                placeholder="请选择渠道类型"
                onChange={(value) => {
                  setCurrentChannelType(value);
                }}
              >
                <Select.Option value="wechat">微信支付</Select.Option>
                <Select.Option value="alipay">支付宝</Select.Option>
                <Select.Option value="unionpay">银联支付</Select.Option>
                <Select.Option value="balance">余额支付</Select.Option>
              </Select>
            </Form.Item>
            
            <Form.Item
              name="fee_rate"
              label="手续费率(%)"
              rules={[{ required: true, message: '请输入手续费率' }]}
            >
              <Input type="number" placeholder="请输入手续费率" />
            </Form.Item>
            
            <Form.Item
              name="status"
              label="状态"
              valuePropName="checked"
            >
              <Switch checkedChildren="启用" unCheckedChildren="禁用" />
            </Form.Item>
            
            {renderChannelFormItems()}
          </Form>
        </Modal>
      </Card>
    </PageContainer>
  );
};
export default PaymentChannelConfig;